const NewsModel = require("../model/news");
const BaseController = require("./base/base");
const Result = require("../utils/result");
class NewsController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 获取新闻列表
  findNewsList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize = 5, page = 1, news_name = '', communities = '', creator = '' } = req.query;
        pagesize *= 1
        page *= 1
        let start = (page - 1) * pagesize;
        const _filter = { news_name: { $regex: news_name, $options: 'i' }, communities: { $regex: communities, $options: 'i' }, creator: { $regex: creator, $options: 'i' } }
        let list = await NewsModel.find(_filter).limit(pagesize).skip(start)
        let total = await NewsModel.countDocuments(_filter)
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加新闻
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { news_name = '', communities = '', star_num = 0, creator = '', add_time } = req.body;
        star_num *= 1
        if (!news_name) return res.json(Result.fail("新闻名不能为空"));
        if (!communities) return res.json(Result.fail("所属社团不能为空"));
        if (!creator) return res.json(Result.fail("创建者不能为空"));
        const ret = await NewsModel.create({ news_name, communities, star_num, creator, add_time });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改公告信息
  updateNews(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await NewsModel.updateOne({ _id: id }, req.body);
        if (ret.matchedCount != 1) return res.json(Result.fail("修改失败", ret))
        res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除公告
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await NewsModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new NewsController().resolve();